import { Image, Text, View} from '@tarojs/components';
import {useEffect} from "react";
import Taro, { useRouter } from '@tarojs/taro';
import {Navbar, Loading, TextEllipsis, Button, Tag, Empty, Flex} from "@taroify/core";
import { ArrowLeft } from "@taroify/icons";
import { useAgentSelector, useDispatchAgent } from "@/hooks/agent";
import {useConservationSelector, useDispatchConservation} from "@/hooks/conservation";
import {isLogin} from "@/utils/auth";
import {ConservationItemCard} from "@/components";
import {ConservationRes} from "@/types/conservationType";
import './index.css';


export default function AgentDisplay() {
  const router = useRouter();
  const agent_uuid = router.params.uuid;
  const dispatchAgent = useDispatchAgent();
  const dispatchConservation = useDispatchConservation();
  const conservations = useConservationSelector(state => state.conservation.conservations);
  const agentDetail = useAgentSelector(state => state.agent.agentDetail);
  const status = useAgentSelector(state => state.agent.status);
  const is_login = isLogin()
  const returnDialoguePage = async () => {
    await Taro.navigateBack({
      delta: 1
    })
  };

  useEffect(() => {
    if(!is_login){
      Taro.redirectTo({
        url: `/pages/auth/login/index`,
      }).then(_ => Taro.showToast({
        title: '请先注册',
        icon: 'none'
      }));
    }
    if (agent_uuid) {
      dispatchConservation.getAllConservations({agent_uuid: agent_uuid})
      dispatchAgent.getAgentDetail(agent_uuid);
    }
  }, [agent_uuid]);

  const handleNewConservation = async () => {
    if (agentDetail) {
      try {
        const action = await dispatchConservation.addConservation({
          name: `新会话 @${agentDetail.name}`,
          agent_uuid: agentDetail.uuid
        });

        // 使用类型断言明确 action.payload 的类型
        const conservationRes = action.payload as ConservationRes;

        await Taro.navigateTo({
          url: `/pages/agentConservation/index?uuid=${conservationRes.uuid}`,
        });
      } catch (error) {
        console.error('创建会话失败:', error);
      }
    } else {
      console.error('agentDetail 未定义');
    }
  };


  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;


  return (
    <View style={{ height: '100vh', width: '100vw', backgroundColor: 'white'}}>
      {/* 导航栏 */}
      <Navbar
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)',
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft icon={<ArrowLeft onClick={returnDialoguePage} size={25} color='black' />} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black', fontWeight: 'bold' }}>
          {agentDetail ? agentDetail.name : "加载中..."}
        </Navbar.Title>
      </Navbar>
      <View style={{ width: '100%', height: `calc(100% - ${(statusBarHeight || 0) + 150}rpx)`, overflowY: 'auto' }}>
        {/* 主体内容 */}
        {agentDetail ? (
          <View style={{ width: '100%', height: `100%` }}>
            {/* 头像 */}
            <View style={{ padding: '40rpx 0', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column'}}>
              <Image
                src={`${process.env.TARO_APP_BASE_URL}${agentDetail.cover_image}`}
                style={{ width: '300rpx', height: '300rpx', objectFit: 'cover', borderRadius: '50%', boxShadow: '0 4rpx 20rpx rgba(0, 0, 0, 0.1)' }}
              />
              <Text style={{ fontSize: '40rpx', fontWeight: 'bold', textAlign: 'center', marginBottom: '20rpx', marginTop: '20rpx'}}>
                {agentDetail.name}
              </Text>
            </View>
            {/* 名称和描述 */}
            <View style={{ padding: '0 40rpx' }}>
              <TextEllipsis
                content={agentDetail.description}
                rows={3}
                expandText='展开'
                collapseText='收起'
                style={{ fontSize: '28rpx', color: '#666', lineHeight: '1.6' }}
              />
            </View>

            {/* 开始聊天按钮 */}
            <View style={{ padding: '40rpx', display: 'flex', justifyContent: 'center' }}>
              <Button
                onClick={handleNewConservation}
                style={{
                  background: 'linear-gradient(135deg, #6a11cb, #2575fc)',
                  color: '#fff',
                  borderRadius: '50rpx',
                  padding: '20rpx 60rpx',
                  boxShadow: '0 4rpx 10rpx rgba(0, 123, 255, 0.3)',
                }}
              >
                开启新对话
              </Button>
            </View>

            {/* 历史会话列表 */}
            <View style={{ margin: '20rpx', padding: '10rpx', borderRadius: '20rpx', overflow: 'hidden', boxShadow: '0 4rpx 10rpx rgba(0, 0, 0, 0.1)' }}>
              <Tag color='primary'>历史会话</Tag>
              <View>
                {conservations?.items?.map((item, index) => (
                  <ConservationItemCard conservation={item} key={index} />
                ))}
                <View style={{width: '100%', display: 'flex', justifyContent: "center"}}>
                  {status === 'loading' && <Loading>加载中...</Loading>}
                </View>
              </View>
              {conservations?.items?.length === 0 &&
                <Empty>
                  <Empty.Image />
                  <Empty.Description>暂无历史会话，快去开启新聊天！</Empty.Description>
                </Empty>
              }
            </View>
          </View>
        ) : (
          <Flex justify='center'>
            <Empty>
              <Empty.Image src='network' />
              <Empty.Description>加载中</Empty.Description>
              <Loading type='spinner' />
            </Empty>
          </Flex>
        )}
      </View>
    </View>
  );
}
